/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.nifi.processors;

import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.annotation.behavior.ReadsAttribute;
import org.apache.nifi.annotation.behavior.ReadsAttributes;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.util.StandardValidators;
import org.nifi.processors.config.DataAccessProperties;
import org.nifi.processors.model.Res;
import org.nifi.processors.utils.JsonUtils;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Tags({"esgcc", "requst"})
@CapabilityDescription("Esgcc request")
@SeeAlso({})
@ReadsAttributes({@ReadsAttribute(attribute="", description="")})
@WritesAttributes({@WritesAttribute(attribute="", description="")})
public class EsgccRequestProcessor extends AbstractProcessor {

    public static final PropertyDescriptor APP_ID = new PropertyDescriptor
            .Builder().name("APP_ID")
            .displayName("App Id")
            .description("App id Property")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();
            
    public static final PropertyDescriptor URL = new PropertyDescriptor
            .Builder().name("URL")
            .displayName("URL")
            .description("请求URL")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();
            
    public static final PropertyDescriptor ADDRESS = new PropertyDescriptor
            .Builder().name("ADDRESS")
            .displayName("Address")
            .description("请求地址")
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();
            
    public static final PropertyDescriptor TOKEN = new PropertyDescriptor
            .Builder().name("TOKEN")
            .displayName("Token")
            .description("认证Token")
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .required(false)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();
            
    public static final PropertyDescriptor PUBLIC_KEY = new PropertyDescriptor
            .Builder().name("PUBLIC_KEY")
            .displayName("Public Key")
            .description("公钥")
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();

    public static final Relationship SUCCESS = new Relationship.Builder()
            .name("success")
            .description("请求成功")
            .build();
            
    public static final Relationship FAILURE = new Relationship.Builder()
            .name("failure")
            .description("请求失败")
            .build();

    private List<PropertyDescriptor> descriptors;

    private Set<Relationship> relationships;

    private DataAccessProperties dataAccessProperties;

    @Override
    protected void init(final ProcessorInitializationContext context) {
        descriptors = new ArrayList<>();
        descriptors.add(APP_ID);
        descriptors.add(URL);
        descriptors.add(ADDRESS);
        descriptors.add(TOKEN);
        descriptors.add(PUBLIC_KEY);
        descriptors = Collections.unmodifiableList(descriptors);

        relationships = new HashSet<>();
        relationships.add(SUCCESS);
        relationships.add(FAILURE);
        relationships = Collections.unmodifiableSet(relationships);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return this.relationships;
    }

    @Override
    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return descriptors;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {

    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }
        
        try {
            // 获取所有属性值
            final String appId = context.getProperty(APP_ID).evaluateAttributeExpressions(flowFile).getValue();
            final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
            final String address = context.getProperty(ADDRESS).evaluateAttributeExpressions(flowFile).getValue();
            final String token = context.getProperty(TOKEN).evaluateAttributeExpressions(flowFile).getValue();
            final String publicKey = context.getProperty(PUBLIC_KEY).evaluateAttributeExpressions(flowFile).getValue();

            dataAccessProperties = DataAccessProperties.builder()
                    .appId(appId)
                    .address(address)
                    .publicKey(publicKey)
                    .tokenUrl("/zjdata/api/zjdata/v1/token")
                    .timeout(Duration.ofSeconds(10))
                    .build();

            DataAccessService dataAccessService = new DataAccessService(dataAccessProperties);
            Res res = dataAccessService.post(address + url, token, true);

//            // 构建属性内容字符串
//            final StringBuilder contentBuilder = new StringBuilder();
//            contentBuilder.append("APP_ID: ").append(appId).append("\n");
//            contentBuilder.append("URL: ").append(url).append("\n");
//            contentBuilder.append("ADDRESS: ").append(address).append("\n");
//            contentBuilder.append("TOKEN: ").append(token != null ? token : "未提供").append("\n");
//            contentBuilder.append("PUBLIC_KEY: ").append(publicKey).append("\n");
            
            // 将属性内容写入FlowFile
            flowFile = session.write(flowFile, outputStream -> {
                outputStream.write(JsonUtils.serializeJson(res).getBytes());
            });
            
            // 添加属性到FlowFile
            flowFile = session.putAttribute(flowFile, "esgcc.processed", "true");
            
            // 将FlowFile传输到成功关系
            session.transfer(flowFile, SUCCESS);
            getLogger().info("成功处理FlowFile: {}", new Object[]{flowFile});
            
        } catch (Exception e) {
            // 发生异常时，将FlowFile传输到失败关系
            session.transfer(flowFile, FAILURE);
            getLogger().error("处理FlowFile时发生错误: {}", new Object[]{flowFile}, e);
        }
    }
}
